<template>
  <a-layout id="components-layout-demo-fixed">
    <a-layout-header :style="{ position: 'fixed', zIndex: 1, width: '100%' }">
      <div class="logo">
          <img src="~assets/img/logo.png" alt="" />
        </div>
    </a-layout-header>
    <a-layout-content :style="{ padding: '0 50px', marginTop: '64px' }">
      <a-breadcrumb :style="{ margin: '16px 0' }">
        <a-breadcrumb-item>求职小助手-后台管理系统</a-breadcrumb-item>
        <a-breadcrumb-item @click.native="backPage" class="back">题库管理</a-breadcrumb-item>
        <a-breadcrumb-item>题库详情--{{bankTitle}}</a-breadcrumb-item>
      </a-breadcrumb>
      <div
        :style="{
          background: '#fff',
          padding: '40px',
          minHeight: 'calc(100vh - 65px)',
        }"
      >
        <div class="add-question">
          <a-button type="primary" @click="toAddQuestion">
            <a-icon type="plus" /> 添加题目
          </a-button>
          <a-drawer
            title="添加题目"
            :width="720"
            :visible="visible"
            :body-style="{ paddingBottom: '80px' }"
            @close="onClose"
          >
            <a-form :form="form" layout="vertical" hide-required-mark>
              <a-row :gutter="16">
                <a-col :span="24">
                  <a-form-item label="新增问题">
                    <a-textarea
                      v-decorator="[
                        'question',
                        {
                          rules: [
                            {
                              required: true,
                              message: '输入的问题不能为空',
                            },
                          ],
                        },
                      ]"
                      :rows="5"
                      placeholder="请输入问题"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="16">
                <a-col :span="24">
                  <a-form-item label="问题答案">
                    <a-textarea
                      v-decorator="['answer']"
                      :rows="5"
                      placeholder="请输入问题答案（可选）"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
            <div
              :style="{
                position: 'absolute',
                right: 0,
                bottom: 0,
                width: '100%',
                borderTop: '1px solid #e9e9e9',
                padding: '10px 16px',
                background: '#fff',
                textAlign: 'right',
                zIndex: 1,
              }"
            >
              <a-button :style="{ marginRight: '8px' }" @click="onClose">
                取消
              </a-button>
              <a-button type="primary" @click="addQuestion"> 添加 </a-button>
            </div>
          </a-drawer>
        </div>
        <a-table
          :columns="columns"
          :data-source="data"
          :pagination="pagination"
          :loading="loading"
          @change="handleTableChange"
          bordered
        >
          <template
            v-for="col in ['question', 'answer', 'operation']"
            :slot="col"
            slot-scope="text, record"
          >
            <div :key="col">
              <a-input
                v-if="record.editable"
                style="margin: -5px 0"
                :value="text"
                @change="(e) => handleChange(e.target.value, record.key, col)"
              />
              <template v-else>
                {{ text }}
              </template>
            </div>
          </template>
          <template slot="operation" slot-scope="text, record">
            <div class="editable-row-operations">
              <span v-if="record.editable">
                <a @click="() => save(record.key)">保存</a>
                <a-popconfirm
                  title="Sure to cancel?"
                  @confirm="() => cancel(record.key)"
                >
                  <a>取消</a>
                </a-popconfirm>
                <!-- <a-popconfirm
                  title="确定删除吗?"
                  @confirm="() => remove(record.key)"
                >
                  <a>删除</a>
                </a-popconfirm> -->
              </span>
              <span v-else>
                <a :disabled="editingKey !== ''" @click="() => edit(record.key)"
                  >编辑</a
                >
                <a @click="() => remove(record.key)">删除</a>
              </span>
            </div>
          </template>
        </a-table>
      </div>
    </a-layout-content>
    <a-layout-footer :style="{ textAlign: 'center' }">
      Ant Design ©2018 Created by Ant UED
    </a-layout-footer>
  </a-layout>
</template>

<script>
const columns = [
  {
    title: "问题",
    dataIndex: "question",
    width: "35%",
    scopedSlots: { customRender: "question" },
  },
  {
    title: "答案",
    dataIndex: "answer",
    width: "50%",
    scopedSlots: { customRender: "answer" },
  },
  {
    title: "操作",
    dataIndex: "operation",
    width: "15%",
    align: "center",
    scopedSlots: { customRender: "operation" },
  },
];
const data = [
  {
    key: 1,
    question: "问题111111",
    answer: "答案111111",
  },
  {
    key: 2,
    question: "问题111112",
    answer: "答案111111",
  },
  {
    key: 3,
    question: "问题111113",
    answer: "答案111111",
  },
  {
    key: 4,
    question: "问题111113",
    answer: "答案111111",
  },
  {
    key: 5,
    question: "问题111113",
    answer: "答案111111",
  },
  {
    key: 6,
    question: "问题111113",
    answer: "答案111111",
  },
];
import QuestionItem from "./childComps/QuestionItem.vue";
import {
  bankDetail,
  addQuestion,
  deleteQuestion,
  editQuestion,
} from "../../network/bank";
export default {
  name: "BankDetail",
  components: {
    QuestionItem,
  },
  data() {
    return {
      bankId: "",
      bankTitle: "",
      data: [],
      cacheData: [],
      columns,
      editingKey: "",
      loading: false,
      pagination: {
        hideOnSinglePage: true,
        defaultPageSize: 12,
        showQuickJumper: true,
      },
      form: this.$form.createForm(this),
      visible: false,
    };
  },
  mounted() {
    this.bankId = this.$route.params.id;
    // console.log('bankId', this.bankId);
    // this.fetch();
    this.getBankDetail();
  },
  methods: {
    backPage() {
      this.$router.push({path: '/main/bankManage'})
    },
    async getBankDetail() {
      const res = await bankDetail(this.bankId);
      if (res.data.code === 200) {
        console.log(res);
        this.bankTitle = res.data.data.tag;
        console.log(this.bankTitle);
        this.data = res.data.data.list;
      }
    },
    handleChange(value, key, column) {
      // console.log('value', value);
      // console.log('key', key);
      // console.log('column', column);
      const newData = [...this.data];
      const target = newData.filter((item) => key === item.key)[0];
      if (target) {
        target[column] = value;
        this.data = newData;
      }
    },
    edit(key) {
      const newData = [...this.data];
      const target = newData.filter((item) => key === item.key)[0];
      this.editingKey = key;
      if (target) {
        target.editable = true;
        this.data = newData;
      }
    },
    async save(key) {
      console.log(key);
      this.cacheData = this.data.map((item) => ({ ...item }));
      const newData = [...this.data];
      const newCacheData = [...this.cacheData];
      const target = newData.filter((item) => key === item.key)[0];
      const targetCache = newCacheData.filter((item) => key === item.key)[0];
      if (target && targetCache) {
        delete target.editable;
        this.data = newData;
        Object.assign(targetCache, target);
        this.cacheData = newCacheData;
        const { question, answer, key } = targetCache;
        console.log(question, answer, key);
        const params = {
          question,
          answer,
          _id: this.bankId,
          questionId: key,
        }
        const res = await editQuestion(params)
        if (res.data.code === 200) {
          console.log(res);
          this.$message.success('保存成功')
        } else {
          // this.$message.error('保存出错')
        }
      }
      this.editingKey = "";
    },
    cancel(key) {
      const newData = [...this.data];
      const target = newData.filter((item) => key === item.key)[0];
      this.editingKey = "";
      if (target) {
        Object.assign(
          target,
          this.cacheData.filter((item) => key === item.key)[0]
        );
        delete target.editable;
        this.data = newData;
      }
    },
    async remove(key) {
      console.log(key);
      const self = this;
      this.$confirm({
        title: "删除题目",
        content: "确定删除该题目吗",
        okText: "确认",
        cancelText: "取消",
        async onOk() {
          const obj = {
            id: self.bankId,
            questionId: key,
          };
          const res = await deleteQuestion(obj);
          if (res.data.code === 200) {
            console.log(res);
            self.getBankDetail()
            self.$message.success("删除题目成功");
          } else {
            self.$message.error("删除题库失败");
          }
        },
        onCancel() {
          // self.$message.info('取消退出登录');
        },
      });
    },
    handleTableChange(pagination, filters, sorter) {
      console.log(pagination);
      const pager = { ...this.pagination };
      pager.current = pagination.current;
      this.pagination = pager;
      this.fetch({
        results: pagination.pageSize,
        page: pagination.current,
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters,
      });
    },
    fetch(params = {}) {
      console.log("params:", params);
      this.loading = true;

      bankDetail(this.bankId).then((res) => {
        if (res.data.code === 200) {
          this.bankTitle = res.data.data.tag;
          this.data = res.data.data.list;
          const pagination = { ...this.pagination };
          pagination.total = this.data.length;
          this.loading = false;
          this.pagination = pagination;
        }
      });

      // reqwest({
      //   url: "https://randomuser.me/api",
      //   method: "get",
      //   data: {
      //     results: 10,
      //     ...params,
      //   },
      //   type: "json",
      // }).then((data) => {
      //   const pagination = { ...this.pagination };
      //   // Read total count from server
      //   // pagination.total = data.totalCount;
      //   pagination.total = 200;
      //   this.loading = false;
      //   this.data = data.results;
      //   this.pagination = pagination;
      // });
    },
    toAddQuestion() {
      this.visible = true;
    },
    onClose() {
      this.visible = false;
    },
    addQuestion(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log("Received values of form: ", values);
          const obj = {
            id: this.bankId,
            list: [values],
          };
          addQuestion(obj).then((res) => {
            if (res.data.code === 200) {
              this.$message.success("添加题目成功");
              this.getBankDetail();
              this.onClose();
            } else {
              this.$message.error("添加失败");
            }
          });
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
#components-layout-demo-fixed .logo {
  width: 120px;
  height: 31px;
  background: rgba(255, 255, 255, 0.2);
  margin: 16px 24px 16px 0;
  float: left;
  text-align: center;
  line-height: 31px;
  img {
    width: 58px;
    height: 20px;
  }
}

.editable-row-operations a {
  margin-right: 8px;
}

.add-question {
  margin-bottom: 20px;
}

.back {
  cursor: pointer;
  &:hover {
    color: #041527;
  }
}
</style>
